import Vuex from '@wepy/x';
import {
    ADDRESSDIDCHANGE,
    CHAOSHICARTCHANGE,
    CITYDIDCHANGE,
    LOCATIONDIDCHANGE, SETTINGSDIDCHANGE,
    SIGNIN,
    SIGNOUT,
    WAIMAICARTCHANGE
} from './type';
import { AccessTokenKey } from '@/config';
import ApiClient from '@/utils/ApiClient';

const store = new Vuex.Store({
    state: {
        location: {
            latitude: 0,
            longitude: 0,
            speed: -1,
            accuracy: 65,
            verticalAccuracy: 65,
            horizontalAccuracy: 65
        },
        isSignined: false,
        userInfo: {},
        city: {
            name: '',
            lat: 0,
            lng: 0
        },
        address: {},
        shop: null,
        waimaiCart: {
            shop: null,
            products: []
        },
        chaoshiCart: {
            total: 0,
            items: []
        },
        settings: {}
    },
    mutations: {
        [SIGNIN](state, userInfo) {
            state.isSignined = true;
            state.userInfo = userInfo;
        },
        [SIGNOUT](state) {
            wx.removeStorageSync(AccessTokenKey);
            state.isSignined = false;
            state.userInfo = null;
        },
        [LOCATIONDIDCHANGE](state, location) {
            state.location = location;
        },
        [CITYDIDCHANGE](state, city) {
            state.city = city;
        },
        [ADDRESSDIDCHANGE](state, address) {
            state.address = address;
        },
        [WAIMAICARTCHANGE](state, data) {
            state.waimaiCart = {
                ...state.waimaiCart,
                ...data
            };
        },
        [CHAOSHICARTCHANGE](state, data) {
            state.chaoshiCart = {
                ...state.chaoshiCart,
                ...data
            };
        },
        [SETTINGSDIDCHANGE](state, settings) {
            state.settings = settings;
        }
    },
    actions: {
        syncChaoshiCart({ commit }) {
            ApiClient.get('/chaoshi/cart/list').then(response => {
                commit(CHAOSHICARTCHANGE, response.result);
            });
        },
        fetchSettings({ commit }) {
            ApiClient.get('/settings/list').then(response => {
                let { settings } = response.result;
                commit(SETTINGSDIDCHANGE, settings);
            });
        }
    },
    getters: {
        userInfo(state) {
            return state.userInfo;
        },
        settings(state) {
            return state.settings;
        },
        isSignined(state){
            return state.isSignined;
        }
    }
});


module.exports = store;
